<?php

namespace Common\Taglib;

use Common\Lib\Relation;

class question
{
    public function run($opt)
    {
        $order     = 'id desc';
        $type      = trim($opt['type']);
        $field     = trim($opt['field']);
        $num       = empty($opt['num']) ? 10 : intval($opt['num']);
        $tagid     = intval($opt['tagid']);
        $page      = $opt['page'];
        $page      = intval($page);
        $startrow  = intval($opt['startrow']);
        $key       = trim($opt['key']);
        $category1 = intval($opt['category1']);
        $category2 = intval($opt['category2']);
        $uid       = intval($opt['uid']);
		$ids = trim($opt['ids']);
        $answernum = intval($opt['answernum']);
        $praisenum = intval($opt['praisenum']);

        $map = array();
        $map = array_merge($map, D('Question')->map_audit(3));
        $map = array_merge($map, D('Question')->map_category($category1, $category2));
        if ($uid > 0) {
            $map['uid'] = $uid;
        }
        if (!empty($type)) {
            $map = array_merge($map, D('Question')->map_order($type));
        }
        if (!empty($key)) {
            $map = array_merge($map, D('Question')->map_keywords($key));
        }
        if (!empty($tagid)) {
            $map = array_merge($map, D('Question')->map_tag($tagid));
        }
		if (!empty($ids) && is_match_ids($ids)) {
            $map['id'] = array('IN',"{$ids}");
        }
        $result = D('Question')->get_list($map, $page, $order, $num, $startrow);

        $list = $result['list'];
        $list = Relation::belongsTo($list, 'User', 'uid', 'uid', 'adduser', array(D('User'), 'auto_user_fill'));
        $list = Relation::belongsTo($list, 'User', 'answeruid', 'uid', 'replyuser', array(D('User'), 'auto_user_fill'));
        $list = Relation::hasMany($list, 'QuestionTag', 'id', 'qid', 'tags', array(D('Tag'), 'tags_fill'));
        $list = Relation::hasMany($list, 'QuestionImg', 'id', 'qid', 'img', function($item){
            // 获取图片url
            foreach ($item as $key => $val) {
                $imgid = $val['img'];
                $item[$key]['url'] = uploadimgurl($imgid);
            }
            return $item;
        });

        if ($answernum > 0) {
            $list = Relation::hasManyLimit($answernum, $list, 'Answer', 'id', 'qid', 'answers', true);
        }

        if ($praisenum > 0) {
            $list = Relation::hasManyLimit($praisenum, $list, 'QuestionPraise', 'id', 'qid', 'praise', true);
        }
        // 返回结果集
        $result['list']  = $list;

        return $result;
    }
}
?>